import React from 'react';
import {
    View,
    Text,
    ScrollView,
    TouchableOpacity, Image, DeviceEventEmitter, Alert,
} from 'react-native';
import {
    InputItem,
    List,
    Switch,
    ActionSheet,
    DatePicker,
    TextareaItem,
    Button,
    Toast,
    ImagePicker
} from '@ant-design/react-native';
import Dict from '../../common/Dict';
import FormItem from "../../common/components/FormItem";
import FormRadioItem from "../../common/components/FormRadioItem";
import GlobalStyles from "../../common/styles/GlobalStyles";
import PickerViewModalCas from '../../common/components/PickerViewModalCas';
import StorageUtil from '../../utils/StorageUtil';
import {Constant} from '../../common/Constant';
import Utils from '../../utils/Utils';
import {BASE_URL} from '../../common/BASE_URL';
import HttpUtils from "../../expand/dao/HttpUtils";
import ToastUtil from "../../utils/ToastUtil";
import NavigationBar from "../../common/NavigationBar";
import styles from "./styles";
import "../../utils/fomat.js"
import TextInputItem from "../../common/components/inputItem";


const getDocumentTemplateUrl = BASE_URL.apiBaseUrl + '/api/document/applyJudge'
const TextToPdf = BASE_URL.apiBaseUrl + '/api/text/replaceTextToPdf'
const temporaryToPdf = BASE_URL.apiBaseUrl + '/api/text/replaceTextToPdf/temporary'

// 制作文书
export default class MakeCaseDocumentForm extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            sexDict: [],
            idTypeDict: [],
            checkTypeList: [],
            showDatetimePicker: false,
            showDatePicker: false,
            documentItem: {},
            documentTemplate: {},
            textForm: {},
            dataForm: {},
            caseInfoVo: {
                caseTitle:'',
                undertaker: '',
                undertakerName: '',
                undertaker2: '',
                undertaker2Name: '',
                // 部门
                undertakerDept:'',
                undertakerDeptLabel : '',
                // 地址
                caseAddress: '',
                contactIdType: '',
                contactIdTypeLabel: '',
                caseTime: '',
                caseTimeStr: '',
                inspectionEndTime: '',
                inspectionEndTimeStr: '',
                // 行业类型
                caseRelatedIndustries: '',
                relatedIndustrieLabel: '',
                // 检查类型
                checkTypeId: '',
                checkTypeLabel: '',
                // 巡查类型
                inspectionItems: [],
                // 案件来源
                caseSourceType: '',
                sourceTypeLable: '',
                // 处罚类型
                punishType: '',
                punishTypeLabel: '',
                // 处罚金额
                punishAmount: null,
                // 案件说明
                caseDescription: '',
                // 案由
                caseBrief: '',
            },
            //新增：1,详情：2 ,编辑：3
            editType:1,
            editIndex:null,
        };
    }

    componentWillMount(){
        let {type}=this.props.navigation.state.params
        this.setState({
            editType:type
        })
    }

    //
    async componentDidMount(){
        const {item,type} = this.props.navigation.state.params;
        if(item && (item.value||item.type)){
            const key = ToastUtil.loading('加载中...')
            HttpUtils.request({
                url: getDocumentTemplateUrl,
                params: {
                    classify: item.value||item.type
                }
            }).then(res=>{
                ToastUtil.remove(key)
                // {
                //  "actionFlow": null, "applyArea": null, "applyDept": null, "applyOrganization": null, "area": null,
                //  "classify": "WSXC", "code": "WSXC", "dept": null,
                //  "documentConfigs": [{"content": "", "dateFormat": "", "documentField": "img", "documentId": 804, "id": 12, "isRequired": 0, "label": "上传图片", "line": 1, "objFi"options": "[{\"label\":\"\",\"value\":\"\"}]", "picQuantity": null, "type": "upload"}, {"content": "", "dateFormat": "yyyy-MM-dd HH:mm:ss", "documentField": "starttime", "documentId": 804, "id": 13, "isRequired": 0, "label": "巡查开始时间", "line": 1, "objField": "", "options": "[{\"label\":\"\",\"value\":\"\"}]", "picQuantity": null, "type": "timer"}, {"content": "", "dateFormat": "yyyy-MM-dd HH:mm:ss", "documentField": "endtime", "documentId": 804, "id": 14, "isRequired": 0, "label": "巡查结束时间", "line": 1, "objField": "", "options": "[{\"label\":\"\",\"value\":\"\"}]", "picQuantity": null, "type": "timer"}, {"content": "", "dateFormat": "", "documentField": "addr", "documentId": 804, "id": 15, "isRequired": 0, "label": "巡查地点", "line": 1, "objField": "", "options": "[{\"label\":\"\",\"value\":\"\"}]", "picQuantity": null, "type": "input"}, {"content": "", "dateFormat": "", "documentField": "inspection_obj", "documentId": 804, "id": 16, "isRequired": 0, "label": "巡查对象", "line": 1, "objField": "", "options": "[{\"label\":\"\",\"value\":\"\"}]", "picQuantity": null, "type": "input"}, {"content": "", "dateFormat": "", "documentField": "inspection_flag", "documentId": 804, "id": 17, "isRequired": 0, "label": "巡查情况", "line": 1, "objField": "", "options": "[{\"label\":\"\",\"value\":\"\"}]", "picQuantity": null, "type": "input"}, {"content": "", "dateFormat": "", "documentField": "officer", "documentId": 804, "id": 18, "isRequired": 0, "label": "执法人员", "line": 1, "objField": "", "options": "[{\"label\":\"\",\"value\":\"\"}]", "picQuantity": null, "type": "input"}], "documentId": 804, "filePath": "/pdf/template/巡查记录.docx", "flowConfigId": null, "flowId": null, "linkIds": null, "name": "巡查记录", "organization": null, "sortNumber": null, "symbol": null, "updateTime": 1627293293000
                //  }
                // console.log('文书模板： ',res);
                // DeviceEventEmitter.addListener("getInfoFrom",(row)=>{
                //     console.log("row***")
                //     console.log(row)
                // })
                if(type==1){//新增
                    let caseInfo=this.props.navigation.state.params.caseInfo||{} //表单详情
                    let caseLitigants=this.props.navigation.state.params.caseLitigants||[] //人员名单
                    let infoNameList={}

                    infoNameList.firstOfficer=caseInfo.undertakerName//第一执法人
                    infoNameList.secondOfficer=caseInfo.undertaker2Name//第二执法人
                    infoNameList.aqcNum=caseInfo.undertakerNum //第一执法人号码
                    infoNameList.aqcNum2=caseInfo.undertakerNum2 //第二执法人号码
                    infoNameList.bothOfficer=(infoNameList.firstOfficer||"未填写")+'、'+(infoNameList.secondOfficer||"未填写") //执法人合集

                    // 执法人合集  含执法证
                    if(infoNameList.firstOfficer){
                        infoNameList.bothOfficerAndAqcNum = infoNameList.firstOfficer+(infoNameList.aqcNum?":"+infoNameList.aqcNum:"")
                    }else{
                        infoNameList.bothOfficerAndAqcNum = "未填写"
                    }
                    if(infoNameList.secondOfficer){
                        infoNameList.bothOfficerAndAqcNum += "、"+infoNameList.secondOfficer+(infoNameList.aqcNum2?":"+infoNameList.aqcNum2:"")
                    }else{
                        infoNameList.bothOfficerAndAqcNum += "、未填写"
                    }
                   
                    infoNameList.startTime=caseInfo.caseTimeStr;//开始时间
                    infoNameList.endTime=caseInfo.inspectionEndTimeStr;//结束时间
                    infoNameList.address=caseInfo.caseAddress;//案件地址
                    infoNameList.sourceType=caseInfo.sourceTypelable//来源类型
                    infoNameList.caseBrief=caseInfo.caseBrief//案由
                    infoNameList.registerReason=caseInfo.caseDescription;//案件说明

                    console.log('caseInfo',caseInfo)

                    if(caseLitigants[0]&&caseLitigants[0].legalPersonName){//法人
                        caseLitigants.forEach((item,index)=>{
                            if(index === 0){
                                infoNameList.unitName=item.unitName||'';//名称 单位名称
                                infoNameList.creditCode=item.socialCreditCode?item.socialCreditCode:'';//统一社会信用代码
                                infoNameList.principal=item.legalPersonName?item.legalPersonName:'';//法人姓名/负责人
                                infoNameList.name=item.contactName?item.contactName:'';//联系人名称
                                infoNameList.idCard=item.contactIdNumber?item.contactIdNumber:'';//证件号码
                                infoNameList.principalAddress=item.contactAddress?item.contactAddress:'';//联系地址
                                infoNameList.phone=item.contactPhone?item.contactPhone:'';//联系电话
                            }else {
                                infoNameList.unitName+=item.unitName?("、"+item.unitName):'';
                                infoNameList.creditCode+=item.socialCreditCode?("、"+item.socialCreditCode):'';
                                infoNameList.principal+=item.legalPersonName?("、"+item.legalPersonName):'';
                                infoNameList.name+=item.contactName?("、"+item.contactName):'';
                                infoNameList.idCard+=item.contactIdNumber?("、"+item.contactIdNumber):'';
                                infoNameList.principalAddress+=item.contactAddress?("、"+item.contactAddress):'';
                                infoNameList.phone+=item.contactPhone?("、"+item.contactPhone):'';
                            }
                        })
                    }else{//个人
                        caseLitigants.forEach((item,index)=>{
                            if(index === 0){
                                infoNameList.unitName=item.contactName||'';//名称  个人名称
                                infoNameList.principal=item.contactName?item.contactName:'';//法人姓名/负责人
                                infoNameList.name=item.contactName?item.contactName:'';//联系人名称
                                infoNameList.idCard=item.contactIdNumber?item.contactIdNumber:'';//证件号码
                                infoNameList.principalAddress=item.contactAddress?item.contactAddress:'';//联系地址
                                infoNameList.phone=item.contactPhone?item.contactPhone:'';//联系电话
                            }else {
                                infoNameList.principal+=item.legalPersonName?("、"+item.legalPersonName):'';//法人姓名
                                infoNameList.unitName+=item.contactName?("、"+item.contactName):'';
                                infoNameList.name+=item.contactName?("、"+item.contactName):'';
                                infoNameList.idCard+=item.contactIdNumber?("、"+item.contactIdNumber):'';
                                infoNameList.principalAddress+=item.contactAddress?("、"+item.contactAddress):'';
                                infoNameList.phone+=item.contactPhone?("、"+item.contactPhone):'';
                            }
                        })
                    }

                    
            
                    let data={}//文书实列参数

                    console.log("res.documentConfigs")
                    console.log(res.documentConfigs)
                    
                    //给文书实列添加属性
                    res.documentConfigs.forEach((item)=>{
                        if(item.type === 'timer'||item.type === 'date'){
                            data[item.documentField+'Str']=null
                        }else{
                            data[item.documentField]=null
                        }
                    })

                    //给文书实列 匹配字典 获取有值的项并赋值，无值不操做
                    res.documentConfigs.forEach((item,index)=>{
                        for(let i in infoNameList){
                            if(item.objField==i){
                                if(item.type === 'timer'||item.type === 'date'){
                                    data[item.documentField+'Str']=infoNameList[i]
                                }else{
                                    data[item.documentField]=infoNameList[i]
                                }
                            }
                        }
                    })
            
                    if(res && !res.status) {
                        this.setState({
                            textForm:{
                                name: res.name,
                                type: res.classify,
                                linkIds: res.linkIds
                            },
                            documentItem: item,
                            documentTemplate: res,
                            dataForm:data,
                        })
                    }
                }else{//编辑和查看
                  let from=JSON.parse(item.documentContent)
                  this.setState({
                    textForm:item,
                    documentItem: item,
                    documentTemplate: res,
                    dataForm:from,
                    editIndex:item.index
                  })
                }
            }).catch(()=>{
                ToastUtil.remove(key)
            })
        }
    }


    _changeFormData(key,value,type){
        let update = {};
        if(type === 'select'){
            update = {
                [key]: value.value[0],
                [key+'Label']: value.label[0],
            };
        }else if(type=="upload"){
            update = { [key]: []};
            if(this.state.dataForm[key]&&this.state.dataForm[key].length>0){
                update[key]=this.state.dataForm[key]
            }
            update[key].push(value)
        }else{
            update = { [key]: value}; 
        }
        const data = Object.assign({}, this.state.dataForm, update);
        this.setState({
            dataForm: data,
        });
        this.props.onChange && this.props.onChange(data)
    }

    _getFormContol(config){
        const {dataForm,editType} = this.state
        console.log(editType) //新增：1,详情：2 ,编辑：3
        // const editType = this.props.navigation.state.params.type;
        // if(){}
        const views = []
        console.log(config)
        if(config){
            config.map((item,index)=>{
                let control;
                const {label, documentField} = item
                if(item.type === 'input'){
                    if(item.line > 1){
                        control = (
                                    editType==1||editType==3?
                                    <View key={index} >
                                        <FormItem label={label} hideIcon={true} maxLength={50} />
                                        <TextareaItem
                                            rows={4}
                                            value={dataForm[documentField]}
                                            onChange={(value) => this._changeFormData(documentField,value)}
                                            placeholder={'请输入' + label}
                                            style={{ paddingVertical: 5,marginLeft: 15,backgroundColor: 'rgba(245, 245, 245, 0.43)' }}
                                        />
                                    </View>
                                    :<FormItem key={index} label={label} value={dataForm[documentField]} hideIcon={true} maxLength={50} />
                                
                         )
                    }else{
                        control = (
                            editType==1||editType==3?
                            // <InputItem
                            //     value={dataForm[documentField]}
                            //     maxLength={200}
                            //     onChange={(value) => this._changeFormData(documentField,value)}
                            //     placeholder={'请输入'+label}
                            // >
                            //     {label}
                            // </InputItem>
                            <TextInputItem
                                key={index} 
                                label={label}
                                placeholder={`请输入${label}`}
                                maxLength={200}
                                value={dataForm[documentField]}
                                onChange={(value)=>{
                                    // let obj={}
                                    // obj[documentField]=value
                                    // let data=Object.assign({},this.state.dataForm,obj)
                                    // this.setState({
                                    //     dataForm:data
                                    // })
                                    this._changeFormData(documentField,value)
                                }}
                            />

                            :<FormItem  label={label} key={index}  value={dataForm[documentField]} hideIcon={true} maxLength={50} />
                        )
                    }
                }else if(item.type === 'date'){
                    control = (
                        editType==1||editType==3?
                        <FormItem
                            key={index} 
                            label={label}
                            placeholder={'请选择'+label}
                            maxLength={50}
                            value={dataForm[documentField+'Str']}
                            onClick={() => {
                                this.datePickerKey = documentField
                                this.setState({showDatePicker: true});
                            }}
                        />:<FormItem
                        key={index} 
                               label={label}
                               maxLength={50}
                               hideIcon={true}
                               value={
                                    new Date(dataForm[documentField+'Str']).Format('yyyy-MM-dd hh:mm:ss')
                               }
                           />
                    )
                }else if(item.type === 'timer'){
                    control = (
                        editType==1||editType==3?
                        <FormItem
                            label={label}
                            key={index} 
                            placeholder={'请选择'+label}
                            maxLength={50}
                            value={dataForm[documentField+'Str']}
                            onClick={() => {
                                this.datePickerKey = documentField
                                this.setState({showDatetimePicker: true});
                            }}
                        />: <FormItem
                           label={label}
                           key={index} 
                           hideIcon={true}
                           maxLength={50}
                           value={
                            new Date(dataForm[documentField+'Str']).Format('yyyy-MM-dd hh:mm:ss')
                           }
                       />
                    )
                }
                else if(item.type === 'upload'){
                    control=(
                        editType==1||editType==3?
                          <FormItem
                            label={label}
                            key={index} 
                            value={dataForm[documentField]}
                            type={item.type}
                            hideIcon={true}
                            onChange={(img) => {
                                this._changeFormData(documentField,img,"upload")
                             }}
                            />:
                            <TouchableOpacity key={index} >
                                <FormItem  label={label} hideIcon={true} maxLength={50} />
                                <Image
                                    style={styles.imageItem}
                                    source={{uri: item.img}}
                                    key={item.uri}
                                />
                            </TouchableOpacity>
                    )
                }
                if(control){
                    views.push(control)
                }
            })
        }
        return views
    }
    _handleSave() {
     //新增：1,详情：2 ,编辑：3
        let type=this.state.editType
        let index=this.state.editIndex
        this.state.dataForm.time = new Date().getTime();
        this.state.textForm.documentContent = JSON.stringify(this.state.dataForm);
        
        if(type==1){//新增：1
            DeviceEventEmitter.emit('addDocumentInfo', {textForm:this.state.textForm,type})
            this.props.navigation.pop()
        }else if(type==3){//编辑
            console.log("编辑")
            console.log(this.state.textForm)
            DeviceEventEmitter.emit('addDocumentInfo', {textForm:this.state.textForm,type,index})
            this.props.navigation.pop()
        }else{
            this.props.navigation.pop()
        }
    }
    render() {
        const {caseInfoVo, documentTemplate,dataForm} = this.state
        let documentConfigs = null //组件集合
        if(documentTemplate){
            documentConfigs = documentTemplate.documentConfigs
        }
        const {type, navigation} = this.props
        const views = this._getFormContol(documentConfigs)
        // const editType=this.props.navigation.state.params.type;
        const editType=this.state.editType;
        const textForm=this.state.textForm
        return (
            <View style={GlobalStyles.pageContainer}>
                {/* 自定义顶部导航条 */}
                <NavigationBar
                    navigation={navigation}
                    headerBackTitle={'制作文书'}
                />
                <View style={[GlobalStyles.innerTabPanel,{flexDirection: 'column',flex: 1}]}>
                    {this._renderHeaderBtns()}
                    <ScrollView
                        style={{flex: 1}}
                        automaticallyAdjustContentInsets={false}
                        showsHorizontalScrollIndicator={false}
                        showsVerticalScrollIndicator={false}>
                        <List>
                            {views}

                            {/*<InputItem*/}
                            {/*    value={caseInfoVo.undertakerName}*/}
                            {/*    maxLength={50}*/}
                            {/*    editable={false}*/}
                            {/*    readonly={true}*/}
                            {/*    placeholder="请输入第一执法人">*/}
                            {/*    第一执法人*/}
                            {/*</InputItem>*/}
                            {/*<FormItem*/}
                            {/*    label={'部门'}*/}
                            {/*    placeholder={'请选择部门'}*/}
                            {/*    maxLength={50}*/}
                            {/*    readonly={true}*/}
                            {/*    value={caseInfoVo.undertakerDeptLabel}*/}
                            {/*    onClick={() => {*/}
                            {/*        // this.refs.typePicker.show();*/}
                            {/*        this.deptDialog.show()*/}
                            {/*    }}*/}
                            {/*/>*/}
                            {/*<FormItem*/}
                            {/*    label={'同行执法人'}*/}
                            {/*    placeholder={'请选择同行执法人'}*/}
                            {/*    maxLength={50}*/}
                            {/*    value={caseInfoVo.undertaker2Name}*/}
                            {/*    onClick={() => {*/}
                            {/*        this.personalDialog.show()*/}
                            {/*    }}*/}
                            {/*/>*/}

                            {/*<FormItem*/}
                            {/*    label={'案件来源'}*/}
                            {/*    placeholder={'请选择案件来源'}*/}
                            {/*    maxLength={50}*/}
                            {/*    value={caseInfoVo.sourceTypeLable}*/}
                            {/*    onClick={() => {*/}
                            {/*        this.showCaseSourceActionSheet()*/}
                            {/*    }}*/}
                            {/*/>*/}
                            {/*<View style={{*/}
                            {/*    flexDirection: 'row',justifyContent: 'space-between',alignItems: 'center',*/}
                            {/*    paddingLeft: 15,paddingRight: 15,paddingTop: 5,paddingBottom: 5,*/}
                            {/*}}>*/}
                            {/*    <Text style={{fontSize: 17}}>案由</Text>*/}
                            {/*    <Text style={{fontSize: 14,color: '#EDAD52',textDecoration: 'underline',}}>点击生成案由</Text>*/}
                            {/*</View>*/}
                            {/*<TextareaItem*/}
                            {/*    rows={4}*/}
                            {/*    value={caseInfoVo.caseBrief}*/}
                            {/*    onChange={(value) => this._changeFormData('caseBrief',value)}*/}
                            {/*    placeholder="请输入案由"*/}
                            {/*    style={{ paddingVertical: 5,marginLeft: 15,backgroundColor: 'rgba(245, 245, 245, 0.43)' }}*/}
                            {/*/>*/}
                            {/*<FormItem*/}
                            {/*    label={'案件说明'}*/}
                            {/*    hideIcon={true}*/}
                            {/*    maxLength={50}*/}
                            {/*/>*/}
                            {/*<TextareaItem*/}
                            {/*    rows={4}*/}
                            {/*    value={caseInfoVo.caseDescription}*/}
                            {/*    onChange={(value) => this._changeFormData('caseDescription',value)}*/}
                            {/*    placeholder="请输入案件说明"*/}
                            {/*    style={{ paddingVertical: 5,marginLeft: 15,backgroundColor: 'rgba(245, 245, 245, 0.43)' }}*/}
                            {/*/>*/}
                        </List>
                    </ScrollView>
                    <View style={styles.bottomBtnsPanel}>
                       {editType==2?
                       <TouchableOpacity
                            style={styles.submitBtn}
                            onPress={()=>this.getPic()}
                        >
                            <Text style={styles.submitBtnText}>生成pdf</Text>
                        </TouchableOpacity>:null}
                        
                        <TouchableOpacity
                            style={styles.submitBtn}
                            onPress={()=>this._handleSave()}
                        >
                        {editType==1||editType==3?
                            <Text style={styles.submitBtnText}>保 存</Text>:
                            <Text style={styles.submitBtnText}>返 回</Text>
                        }

                        </TouchableOpacity>
                    </View>
                    <PickerViewModalCas
                        ref={'typePicker'}
                        colsNum={1}
                        data={this.state.idTypeDict}
                        title={'证件类型'}
                        onChoose={(data) => {
                            // this.setState({selectedPickData: data});
                            this._changeFormData('contactIdType',data, 'select');
                            this.refs.typePicker.hidden();
                        }}
                    />
                    <DatePicker
                        mode="date"
                        visible={this.state.showDatePicker}
                        format="YYYY-MM-DD"
                        value={new Date()}
                        onOk={(date) => {
                            const key = this.datePickerKey
                            const data = Object.assign({}, this.state.dataForm, {
                                [key]: date,
                                [key+'Str']: date.Format('yyyy-MM-dd'),
                            });
                            this.setState({dataForm: data, showDatePicker: false});
                            this.props.onChange && this.props.onChange(data)
                        }}
                        onDismiss={() => this.setState({showDatePicker: false})}
                    />
                    <DatePicker
                        mode="datetime"
                        visible={this.state.showDatetimePicker}
                        format="YYYY-MM-DD hh:mm:ss"
                        value={new Date()}
                        onOk={(date) => {
                            const key = this.datePickerKey
                            const data = Object.assign({}, this.state.dataForm, {
                                [key]: date,
                                [key+'Str']: date.Format('yyyy-MM-dd hh:mm:ss'),
                            });
                            this.setState({dataForm: data, showDatetimePicker: false});
                            this.props.onChange && this.props.onChange(data)
                        }}
                        onDismiss={() => this.setState({showDatetimePicker: false})}
                    />
                </View>
            </View>
        );
    }
    onChoosePersonal(item) {
        this.setState({
            caseInfoVo: {
                ...this.state.caseInfoVo,
                undertaker2: item.officerId,
                undertaker2Name: item.name,
            },
        })
    }
    onChooseDept(item){
        this.setState({
            caseInfoVo: {
                ...this.state.caseInfoVo,
                undertakerDept: item.id,
                undertakerDeptLabel: item.label
            },
        })
    }

    // 处罚类型
    showPunishTypeActionSheet(){
        this.showDictActionSheet('punish_type','punishTypeLabel','punishType')
    }
    // 案件来源
    showCaseSourceActionSheet(){
        this.showDictActionSheet('case_source_type','sourceTypeLable','caseSourceType')
    }
    // 检查类型
    showCheckTypeActionSheet(){
        const typeList = this.state.checkTypeList
        if(!typeList || typeList.length === 0){
            ToastUtil.info('请先选择行业类型')
            return
        }
        const labels = typeList.map((item) => item.name);
        labels.push('关闭');
        const values = typeList.map((item) => item.id);
        ActionSheet.showActionSheetWithOptions(
            {
                options: labels,
                destructiveButtonIndex: labels.length - 1,
                maskClosable: true,
            },
            (index) => {
                if (labels[index] === '关闭') {
                    return false;
                }
                const data = Object.assign({}, this.state.caseInfoVo, {
                    checkTypeId: values[index],
                    checkTypeLabel: labels[index],
                });
                this.setState({caseInfoVo: data});
            },
        );
    }

    // 选择发布类型
    showIndustryTypeActionSheet() {

    }
    async showDictActionSheet(key,label,value,fn){
        let dict = await Dict.getDict(key);
        const labels = dict.map((item) => item.label);
        labels.push('关闭');
        const values = dict.map((item) => item.value);
        ActionSheet.showActionSheetWithOptions(
            {
                options: labels,
                destructiveButtonIndex: labels.length - 1,
                maskClosable: true,
            },
            (index) => {
                if (labels[index] === '关闭') {
                    return false;
                }
                const data = Object.assign({}, this.state.caseInfoVo, {
                    [label]: labels[index],
                    [value]: values[index],
                });
                this.setState({caseInfoVo: data});
                this.props.onChange && this.props.onChange(data)
                fn && fn(values[index])
            },
        );
    }

    getPic(){
        let textFormSave = {}
        textFormSave = this.state.textForm;
        let dataFrom=this.state.dataForm
        textFormSave.documentContent = JSON.stringify(dataFrom);
        let index= this.props.navigation.state.params.dataIndex
        const key = ToastUtil.loading('正在生成pdf')
        if(this.state.textForm.caseCode){
            HttpUtils.request({
                url: TextToPdf,
                type: 'post',
                data: textFormSave,
            }).then((res) => {
                if(res.status==200){
                    Toast.success("生成pdf成功")
                    DeviceEventEmitter.emit('resetCase')
                    this.props.navigation.pop()
                }else{
                    Toast.fail("请将文书补充完整")
                }
            }).finally(()=>{
                ToastUtil.remove(key)
            })
        }else{
            HttpUtils.request({
                url: temporaryToPdf,
                type: 'post',
                data: textFormSave,
            }).then((res) => {
                if(res.status==200){
                    Toast.success("生成pdf成功")
                    let obj={
                        index,
                        path:res.path
                    }
                    DeviceEventEmitter.emit('addCasepath',obj)
                    this.props.navigation.pop()
                }else{
                    Toast.fail("请将文书补充完整")
                }
            }).finally(()=>{
                ToastUtil.remove(key)
            })
        }
       
    }

    _renderHeaderBtns(){
        const {documentItem} = this.state
        return (
            <View style={{flexDirection: 'row',alignItem: 'center',justifyContent: 'center',paddingBottom: 5}}>
                {/*<TouchableOpacity*/}
                {/*    style={{flex: 1}}*/}
                {/*    onPress={()=>this.personalDialog.show()}*/}
                {/*>*/}
                {/*    <Image source={require('../../assets/images/report/report_event.png')} style={{width: '100%',height: 50}} />*/}
                {/*</TouchableOpacity>*/}
                <Text style={{fontSize: 18}}>{documentItem.name?'《'+documentItem.name+'》': ''} </Text>
            </View>
        )
    }

}



